import { useState } from 'react'
import './App.css'

function App() {
  const [inputText, setInputText] = useState('')
  const [translatedText, setTranslatedText] = useState('')
  const [isLoading, setIsLoading] = useState(false)
  const [sourceLang, setSourceLang] = useState('en')
  const [targetLang, setTargetLang] = useState('zh')
  const [error, setError] = useState('')

  const handleTranslate = async () => {
    if (!inputText.trim()) return
    
    setIsLoading(true)
    setError('')
    try {
      const modelName = `${sourceLang}-${targetLang}`
      const response = await fetch('http://localhost:3000/translate', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ 
          modelName,
          text: inputText 
        }),
      });
      
      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.details || errorData.error || '翻译服务出错');
      }
      
      const data = await response.json();
      if (Array.isArray(data) && data.length > 0) {
        setTranslatedText(data[0].translation_text);
      } else {
        throw new Error('翻译结果格式不正确');
      }
    } catch (error) {
      console.error('翻译出错:', error);
      setError(error.message);
      setTranslatedText('');
    } finally {
      setIsLoading(false);
    }
  }

  const swapLanguages = () => {
    setSourceLang(targetLang)
    setTargetLang(sourceLang)
    setInputText(translatedText)
    setTranslatedText(inputText)
    setError('')
  }

  const getLanguageName = (code) => {
    const languages = {
      'zh': '中文（简体）',
      'en': '英语',
      'ja': '日语'
    }
    return languages[code]
  }

  return (
    <div className="translator-container">
      <div className="header">
        <div className="logo">
          <div className="logo-ring"></div>
          <span className="logo-text">AI简翻译</span>
        </div>
        <nav className="nav-tabs">
          <button className="tab active">文字</button>
          <button className="tab">图片</button>
          <button className="tab">文档</button>
          <button className="tab">网站</button>
        </nav>
      </div>

      <div className="translation-box">
        <div className="language-bar">
          <div className="language-selector">
            <select 
              value={sourceLang} 
              onChange={(e) => {
                setSourceLang(e.target.value)
                setError('')
              }}
            >
              {['en', 'zh', 'ja'].map(lang => (
                <option key={lang} value={lang}>
                  {getLanguageName(lang)}
                </option>
              ))}
            </select>
          </div>
          <button className="swap-btn" onClick={swapLanguages}>⇄</button>
          <div className="language-selector">
            <select 
              value={targetLang} 
              onChange={(e) => {
                setTargetLang(e.target.value)
                setError('')
              }}
            >
              {['zh', 'en', 'ja'].map(lang => (
                <option key={lang} value={lang}>
                  {getLanguageName(lang)}
                </option>
              ))}
            </select>
          </div>
        </div>

        <div className="translation-area">
          <div className="input-section">
            <textarea
              value={inputText}
              onChange={(e) => {
                setInputText(e.target.value)
                setError('')
              }}
              placeholder={`请输入${getLanguageName(sourceLang)}文本`}
              rows="5"
              onKeyUp={(e) => {
                if (e.key === 'Enter' && !e.shiftKey) {
                  e.preventDefault()
                  handleTranslate()
                }
              }}
            />
            <div className="input-tools">
              <button onClick={() => {
                setInputText('')
                setError('')
              }}>✕</button>
              <button 
                onClick={handleTranslate} 
                disabled={isLoading || !inputText.trim()}
              >
                {isLoading ? '翻译中...' : '翻译'}
              </button>
            </div>
          </div>

          <div className="output-section">
            <textarea
              value={error || translatedText}
              readOnly
              placeholder={`${getLanguageName(targetLang)}翻译结果`}
              rows="5"
              className={error ? 'error' : ''}
            />
            <div className="output-tools">
              <button 
                onClick={() => navigator.clipboard.writeText(translatedText)}
                disabled={!!error || !translatedText}
              >
                复制
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}

export default App
